<template>
  <div class="compiler-page">
    <van-nav-bar
      title="在线编译器"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="compiler-container">
      <div class="language-selector">
        <van-dropdown-menu>
          <van-dropdown-item v-model="selectedLanguage" :options="languageOptions" />
        </van-dropdown-menu>
      </div>
      
      <div class="editor-section">
        <div class="section-header">
          <span class="section-title">源代码</span>
          <div class="actions">
            <van-button size="small" type="primary" :loading="loading" @click="runCode">
              {{ loading ? '运行中...' : '运行' }}
            </van-button>
            <van-button size="small" plain @click="clearCode">清空</van-button>
          </div>
        </div>
        <div class="code-editor">
          <van-field
            v-model="sourceCode"
            type="textarea"
            placeholder="在此输入代码..."
            rows="12"
            autosize
          />
        </div>
        <div class="input-section" v-if="showInput">
          <div class="section-header">
            <span class="section-title">标准输入</span>
            <van-button size="small" plain @click="clearInput">清空</van-button>
          </div>
          <van-field
            v-model="stdin"
            type="textarea"
            placeholder="程序的标准输入（可选）..."
            rows="3"
            autosize
          />
        </div>
      </div>
      
      <div class="output-section">
        <div class="section-header">
          <span class="section-title">运行结果</span>
          <div class="actions">
            <van-switch v-model="showInput" size="20px">
              <template #node>
                <van-icon :name="showInput ? 'eye-o' : 'closed-eye'" size="16" />
              </template>
            </van-switch>
            <van-button size="small" plain @click="clearOutput">清空</van-button>
          </div>
        </div>
        <div class="output-area" :class="{ 'has-error': hasError }">
          <pre><code>{{ output }}</code></pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast } from 'vant'
import { executeCode, LANGUAGE_CONFIG } from '../../../api/jdoodle'

const router = useRouter()

// 更新语言选项以匹配 JDoodle 支持的语言
const languageOptions = [
  { text: 'JavaScript (Node.js)', value: 'javascript' },
  { text: 'Python 3', value: 'python' },
  { text: 'Java', value: 'java' },
  { text: 'C++', value: 'cpp' },
  { text: 'Go', value: 'go' }
]

// 示例代码
const codeExamples = {
  javascript: `// 输出Hello World
console.log('Hello World');

// 计算1到10的和
let sum = 0;
for(let i = 1; i <= 10; i++) {
    sum += i;
}
console.log('Sum:', sum);`,
  
  python: `# 输出Hello World
print('Hello World')

# 计算1到10的和
sum = 0
for i in range(1, 11):
    sum += i
print('Sum:', sum)`,
  
  java: `public class Main {
    public static void main(String[] args) {
        // 输出Hello World
        System.out.println("Hello World");
        
        // 计算1到10的和
        int sum = 0;
        for(int i = 1; i <= 10; i++) {
            sum += i;
        }
        System.out.println("Sum: " + sum);
    }
}`,
  
  cpp: `#include <iostream>
using namespace std;

int main() {
    // 输出Hello World
    cout << "Hello World" << endl;
    
    // 计算1到10的和
    int sum = 0;
    for(int i = 1; i <= 10; i++) {
        sum += i;
    }
    cout << "Sum: " << sum << endl;
    return 0;
}`,
  
  go: `package main

import "fmt"

func main() {
    // 输出Hello World
    fmt.Println("Hello World")
    
    // 计算1到10的和
    sum := 0
    for i := 1; i <= 10; i++ {
        sum += i
    }
    fmt.Println("Sum:", sum)
}`
}

const selectedLanguage = ref('javascript')
const sourceCode = ref(codeExamples.javascript)
const lastSaved = ref('')
const stdin = ref('')
const showInput = ref(false)

// 自动保存功能
let autoSaveTimer = null

const saveCode = () => {
  const saveData = {
    language: selectedLanguage.value,
    code: sourceCode.value,
    timestamp: new Date().getTime()
  }
  localStorage.setItem('compiler_autosave', JSON.stringify(saveData))
  lastSaved.value = '已自动保存 ' + new Date().toLocaleTimeString()
}

// 加载保存的代码
const loadSavedCode = () => {
  const saved = localStorage.getItem('compiler_autosave')
  if (saved) {
    const data = JSON.parse(saved)
    selectedLanguage.value = data.language
    sourceCode.value = data.code
    lastSaved.value = '上次保存于 ' + new Date(data.timestamp).toLocaleString()
  }
}

// 监听代码变化,自动保存
watch(sourceCode, () => {
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer)
  }
  autoSaveTimer = setTimeout(() => {
    saveCode()
  }, 2000) // 2秒后自动保存
})

// 组件挂载时加载保存的代码
onMounted(() => {
  loadSavedCode()
})

// 组件卸载时保存代码
onBeforeUnmount(() => {
  if (sourceCode.value.trim()) {
    saveCode()
  }
})

// 监听语言变化
watch(selectedLanguage, (newLang) => {
  if (sourceCode.value === '' || confirm('切换语言将清空当前代码，是否继续？')) {
    sourceCode.value = codeExamples[newLang]
  }
})

const loading = ref(false)
const output = ref('')
const hasError = ref(false)

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 运行代码
const runCode = async () => {
  if (!sourceCode.value.trim()) {
    showToast('请输入代码')
    return
  }

  loading.value = true
  output.value = ''
  hasError.value = false
  const toast = showLoadingToast({
    message: '编译执行中...',
    forbidClick: true,
  })

  try {
    const result = await executeCode(selectedLanguage.value, sourceCode.value, stdin.value)
    
    if (result.success) {
      output.value = result.output
      if (result.memory || result.cpuTime) {
        output.value += `\n\n--- 执行统计 ---\n内存使用: ${result.memory} KB\n执行时间: ${result.cpuTime} 秒`
      }
    } else {
      hasError.value = true
      output.value = `执行错误: ${result.error}`
    }
  } catch (err) {
    hasError.value = true
    output.value = '运行出错: ' + err.message
  } finally {
    loading.value = false
    toast.close()
  }
}

// 清空代码
const clearCode = () => {
  sourceCode.value = ''
  output.value = ''
  hasError.value = false
}

// 清空输出
const clearOutput = () => {
  output.value = ''
  hasError.value = false
}

// 清空输入
const clearInput = () => {
  stdin.value = ''
}
</script>

<style lang="scss" scoped>
.compiler-page {
  min-height: 100vh;
  position: relative;
  
  .compiler-container {
    padding: 16px;
    
    .language-selector {
      margin-bottom: 16px;
    }
    
    .editor-section,
    .output-section {
      background-color: var(--background-color-light);
      border-radius: 8px;
      margin-bottom: 16px;
      overflow: hidden;
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid var(--border-color);
        
        .section-title {
          font-size: 16px;
          font-weight: 500;
          color: var(--text-color);
        }
        
        .actions {
          display: flex;
          gap: 8px;
          align-items: center;
          
          .van-switch {
            margin-right: 8px;
          }
        }
      }
    }
    
    .code-editor {
      position: relative;
      
      :deep(.van-field__control) {
        font-family: 'Fira Code', Consolas, Monaco, 'Andale Mono', monospace;
        font-size: 14px;
        line-height: 1.5;
        padding: 12px 12px 12px 48px; // 为行号留出空间
        background-color: var(--code-bg-color, #1e1e1e);
        color: var(--code-text-color, #d4d4d4);
        resize: vertical;
        min-height: 300px;
      }

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 36px;
        background-color: var(--code-gutter-bg-color, #2d2d2d);
        border-right: 1px solid var(--border-color);
        z-index: 1;
      }

      &::after {
        content: attr(data-line-numbers);
        position: absolute;
        left: 0;
        top: 12px;
        width: 36px;
        font-family: 'Fira Code', Consolas, Monaco, 'Andale Mono', monospace;
        font-size: 14px;
        line-height: 1.5;
        color: var(--code-line-number-color, #858585);
        text-align: right;
        padding-right: 8px;
        pointer-events: none;
        user-select: none;
      }
    }
    
    .output-area {
      padding: 12px 16px;
      min-height: 100px;
      max-height: 300px;
      overflow-y: auto;
      font-family: 'Fira Code', Consolas, Monaco, 'Andale Mono', monospace;
      font-size: 14px;
      line-height: 1.5;
      white-space: pre-wrap;
      background-color: var(--code-bg-color, #1e1e1e);
      color: var(--code-text-color, #d4d4d4);
      
      &.has-error {
        color: var(--danger-color, #ff4444);
      }
      
      pre {
        margin: 0;
        code {
          display: block;
        }
      }
    }
  }
}

.status-info {
  margin-right: 12px;
  
  .save-status {
    font-size: 12px;
    color: var(--text-color-secondary);
  }
}

.input-section {
  margin-top: 12px;
  border-top: 1px solid var(--border-color);
  padding-top: 12px;
}
</style>